package com.xhx.accounting;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import android.app.DatePickerDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.res.ColorStateList;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class Keyboard extends AppCompatActivity {
    private EditText notes;
    private int type;
    private int currentClassificationId;
    private int accountBookId;
    private TextView Key_finial;
    private TextView Key_clear;

    private TextView optionNum;
    private TextView resultNum;
    private TextView signDisplay;
    private TextView dateDisplay;
    private TextView displayArea;
    private double result_num;
    private String option_num;
    private int sign; //1：加法 -1减法

    private long timeStamp;
    private Calendar calendar;

    private boolean canSubmit;

    private GridView classificationGrid;
    private TextView classifi;
    private View outLine;
    private View inLine;

    private List<Map<String, Object>> mData;
    private classification_grid_item adapter;

    private DBDao db;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_keyboard);

        accountBookId = Integer.parseInt(getIntent().getStringExtra("accountId"));

        db = new DBDao(this);
        mData = new ArrayList<>();

        classificationGrid = findViewById(R.id.gridView);

        //初始数据
        mData.addAll(db.getClassifi(-1));
        outLine = findViewById(R.id.outline);
        inLine = findViewById(R.id.inline);
        notes = findViewById(R.id.editText);
        inLine.setVisibility(View.INVISIBLE);

        adapter = new classification_grid_item(this, mData);
        classificationGrid.setAdapter(adapter);


        classificationGrid.setOnItemClickListener((parent, view, position, id) -> {
            HashMap<String, Object> listinfo = (HashMap<String, Object>) classificationGrid.getItemAtPosition(position);//SimpleAdapter返回Map
            Log.d("onClick", listinfo.toString());
            classifi.setText(listinfo.get("classification_name").toString() + listinfo.get("id").toString());
            currentClassificationId = (int)listinfo.get("id");
            type = (int)listinfo.get("classification_direction");
            for (int i = 0; i < parent.getCount(); i++) {
                View item = classificationGrid.getChildAt(i).findViewById(R.id.imageBg);
                ImageView item2 = classificationGrid.getChildAt(i).findViewById(R.id.imageView2);
                TextView item3 = classificationGrid.getChildAt(i).findViewById(R.id.text);
                if (position == i) {//当前选中的Item改变背景颜色
                    item.setBackgroundResource(R.drawable.grid_down_bg);
                    item2.setImageTintList(ColorStateList.valueOf(ContextCompat.getColor(Keyboard.this,R.color.white)));
                    item3.setTextColor(ColorStateList.valueOf(ContextCompat.getColor(Keyboard.this,R.color.blue_100)));
                } else {
                    item.setBackgroundResource(R.drawable.grid_up_bg);
                    item2.setImageTintList(ColorStateList.valueOf(ContextCompat.getColor(Keyboard.this,R.color.black)));
                    item3.setTextColor(ColorStateList.valueOf(ContextCompat.getColor(Keyboard.this,R.color.black)));
                }
            }
        });

        //初始化键盘
        initKeyboard();

        TextView outBtn = findViewById(R.id.out);
        TextView inBtn = findViewById(R.id.in);

        outBtn.setOnClickListener(v -> {
            setClassification(-1);
            classifi.setText("null");
        });

        inBtn.setOnClickListener(v -> {
            setClassification(1);
            classifi.setText("null");
        });

    }

    private void setClassification(int K) {
        if (K == -1) {
            //支出
            inLine.setVisibility(View.INVISIBLE);
            outLine.setVisibility(View.VISIBLE);
        } else if (K == 1) {
            //收入
            outLine.setVisibility(View.INVISIBLE);
            inLine.setVisibility(View.VISIBLE);
        }
        mData.clear();
        mData.addAll(db.getClassifi(K));
        classificationGrid.setAdapter(adapter);
    }

    private void initKeyboard() {
        calendar = Calendar.getInstance();
        result_num = 0.00;
        option_num = "0";
        canSubmit = true;
        timeStamp = 0;

        classifi = findViewById(R.id.classifi);
        optionNum = findViewById(R.id.option);
        resultNum = findViewById(R.id.result);
        signDisplay = findViewById(R.id.sign);
        dateDisplay = findViewById(R.id.dateDisplay);
        displayArea = findViewById(R.id.displayArea);

        sign = 1;

        TextView key_1 = findViewById(R.id.key_1);
        TextView Key_2 = findViewById(R.id.key_2);
        TextView Key_3 = findViewById(R.id.key_3);
        TextView Key_4 = findViewById(R.id.key_4);
        TextView Key_5 = findViewById(R.id.key_5);
        TextView Key_6 = findViewById(R.id.key_6);
        TextView Key_7 = findViewById(R.id.key_7);
        TextView Key_8 = findViewById(R.id.key_8);
        TextView Key_9 = findViewById(R.id.key_9);
        TextView Key_0 = findViewById(R.id.key_0);
        TextView Key_plus = findViewById(R.id.key_plus);
        TextView Key_minus = findViewById(R.id.key_minus);
        TextView Key_point = findViewById(R.id.key_point);
        Key_finial = findViewById(R.id.key_finish);
        Key_clear = findViewById(R.id.key_clear);
        View key_datePicker = findViewById(R.id.datePicker);

        DecimalFormat decimalFormat = new DecimalFormat("0.00");

        Key_0.setOnClickListener(v -> {
            int delta = option_num.length() - option_num.indexOf(".");

            if (!option_num.contains(".")) {
                if (option_num.equals("0")) {
                    option_num = "";
                }
                option_num = option_num + "0";
                optionNum.setText(option_num);
                displayArea.setText(option_num);
            } else if (delta < 3) {
                option_num = option_num + "0";
                optionNum.setText(option_num);
                displayArea.setText(option_num);
            } else {
                Log.d("over", "true");
            }
        });
        key_1.setOnClickListener(v -> {
            int delta = option_num.length() - option_num.indexOf(".");

            if (!option_num.contains(".")) {
                if (option_num.equals("0")) {
                    option_num = "";
                }
                option_num = option_num + "1";
                optionNum.setText(option_num);
                displayArea.setText(option_num);
            } else if (delta < 3) {
                option_num = option_num + "1";
                optionNum.setText(option_num);
                displayArea.setText(option_num);
            } else {
                Log.d("over", "true");
            }
        });
        Key_2.setOnClickListener(v -> {
            int delta = option_num.length() - option_num.indexOf(".");

            if (!option_num.contains(".")) {
                if (option_num.equals("0")) {
                    option_num = "";
                }
                option_num = option_num + "2";
                optionNum.setText(option_num);
                displayArea.setText(option_num);
            } else if (delta < 3) {
                option_num = option_num + "2";
                optionNum.setText(option_num);
                displayArea.setText(option_num);
            } else {
                Log.d("over", "true");
            }
        });
        Key_3.setOnClickListener(v -> {
            int delta = option_num.length() - option_num.indexOf(".");

            if (!option_num.contains(".")) {
                if (option_num.equals("0")) {
                    option_num = "";
                }
                option_num = option_num + "3";
                optionNum.setText(option_num);
                displayArea.setText(option_num);
            } else if (delta < 3) {
                option_num = option_num + "3";
                optionNum.setText(option_num);
                displayArea.setText(option_num);
            } else {
                Log.d("over", "true");
            }
        });
        Key_4.setOnClickListener(v -> {
            int delta = option_num.length() - option_num.indexOf(".");

            if (!option_num.contains(".")) {
                if (option_num.equals("0")) {
                    option_num = "";
                }
                option_num = option_num + "4";
                optionNum.setText(option_num);
                displayArea.setText(option_num);
            } else if (delta < 3) {
                option_num = option_num + "4";
                optionNum.setText(option_num);
                displayArea.setText(option_num);
            } else {
                Log.d("over", "true");
            }
        });
        Key_5.setOnClickListener(v -> {
            int delta = option_num.length() - option_num.indexOf(".");

            if (!option_num.contains(".")) {
                if (option_num.equals("0")) {
                    option_num = "";
                }
                option_num = option_num + "5";
                optionNum.setText(option_num);
                displayArea.setText(option_num);
            } else if (delta < 3) {
                option_num = option_num + "5";
                optionNum.setText(option_num);
                displayArea.setText(option_num);
            } else {
                Log.d("over", "true");
            }
        });
        Key_6.setOnClickListener(v -> {
            int delta = option_num.length() - option_num.indexOf(".");

            if (!option_num.contains(".")) {
                if (option_num.equals("0")) {
                    option_num = "";
                }
                option_num = option_num + "6";
                optionNum.setText(option_num);
                displayArea.setText(option_num);
            } else if (delta < 3) {
                option_num = option_num + "6";
                optionNum.setText(option_num);
                displayArea.setText(option_num);
            } else {
                Log.d("over", "true");
            }
        });
        Key_7.setOnClickListener(v -> {
            int delta = option_num.length() - option_num.indexOf(".");

            if (!option_num.contains(".")) {
                if (option_num.equals("0")) {
                    option_num = "";
                }
                option_num = option_num + "7";
                optionNum.setText(option_num);
                displayArea.setText(option_num);
            } else if (delta < 3) {
                option_num = option_num + "7";
                optionNum.setText(option_num);
                displayArea.setText(option_num);
            } else {
                Log.d("over", "true");
            }
        });
        Key_8.setOnClickListener(v -> {
            int delta = option_num.length() - option_num.indexOf(".");

            if (!option_num.contains(".")) {
                if (option_num.equals("0")) {
                    option_num = "";
                }
                option_num = option_num + "8";
                optionNum.setText(option_num);
                displayArea.setText(option_num);
            } else if (delta < 3) {
                option_num = option_num + "8";
                optionNum.setText(option_num);
                displayArea.setText(option_num);
            } else {
                Log.d("over", "true");
            }
        });
        Key_9.setOnClickListener(v -> {
            int delta = option_num.length() - option_num.indexOf(".");

            if (!option_num.contains(".")) {
                if (option_num.equals("0")) {
                    option_num = "";
                }
                option_num = option_num + "9";
                optionNum.setText(option_num);
                displayArea.setText(option_num);
            } else if (delta < 3) {
                option_num = option_num + "9";
                optionNum.setText(option_num);
                displayArea.setText(option_num);
            } else {
                Log.d("over", "true");
            }
        });
        Key_point.setOnClickListener(v -> {
            if (!option_num.contains(".")) {
                option_num = option_num + ".";
                optionNum.setText(option_num);
                displayArea.setText(option_num);
            }
        });
        Key_clear.setOnClickListener(v -> {
            result_num = 0.00;
            option_num = "0";

            sign = 1;//下一个是 +
            signDisplay.setText("+");

            canSubmit = true;
            Key_finial.setText("完成");

            displayArea.setText("0");
            optionNum.setText(option_num);
            resultNum.setText("0.00");
        });
        Key_plus.setOnClickListener(v -> {
            result_num = result_num + sign * Double.parseDouble(option_num);
            resultNum.setText(decimalFormat.format(result_num));
            result_num = Double.parseDouble(decimalFormat.format(result_num));
            sign = 1;//下一个是 +
            signDisplay.setText("+");
            canSubmit = false; //禁止直接提交
            Key_finial.setText("=");
            option_num = "0";
            displayArea.setText(option_num);
            optionNum.setText("0");
            resultNum.setText(String.valueOf(result_num));
        });
        Key_minus.setOnClickListener(v -> {
            result_num = result_num + sign * Double.parseDouble(option_num);
            resultNum.setText(decimalFormat.format(result_num));
            result_num = Double.parseDouble(decimalFormat.format(result_num));
            sign = -1;//下一个是 -
            signDisplay.setText("-");
            canSubmit = false; //禁止直接提交
            Key_finial.setText("=");
            displayArea.setText(option_num);
            option_num = "0";
            optionNum.setText("0");
        });
        Key_finial.setOnClickListener(v -> {
            if (canSubmit) {
                //提交流程
                Log.d("Submit", "true");
                result_num = result_num + sign * Double.parseDouble(option_num);
                Log.d("Submit", String.valueOf(result_num));
                //日期
                if (timeStamp == 0) {
                    Calendar now = Calendar.getInstance();// 获取当前日期
                    now.set(Calendar.HOUR_OF_DAY, 0);
                    now.set(Calendar.MINUTE, 0);
                    now.set(Calendar.SECOND, 0);
                    timeStamp = now.getTimeInMillis() / 1000;
                    //
                    Log.d("Submit", String.valueOf(timeStamp));
                } else {
                    Log.d("Submit", String.valueOf(timeStamp));
                }
                ContentValues cv = new ContentValues();
                cv.put("timeStamp",timeStamp);
                cv.put("classification",currentClassificationId);
                cv.put("type",type);
                cv.put("amount",result_num);
                cv.put("notes",notes.getText().toString());
                cv.put("accountBookId",accountBookId);
                Log.d("cv",cv.toString());
                if(db.addAccountRecord(cv)){
                    this.finish();
                };
            } else {
                //等于号流程
                result_num = result_num + sign * Double.parseDouble(option_num);
                resultNum.setText(decimalFormat.format(result_num));
                displayArea.setText(decimalFormat.format(result_num));
                result_num = Double.parseDouble(decimalFormat.format(result_num));
                option_num = "0";
                optionNum.setText("0");
                canSubmit = true;
                Key_finial.setText("完成");
            }
        });
        key_datePicker.setOnClickListener(v -> {
            //显示日期选择器
            showDatePickerDialog(Keyboard.this, 0);
        });
    }

    public void showDatePickerDialog(Context context, int themeResId) {
        new DatePickerDialog(context, themeResId, (view, year, month, dayOfMonth) -> {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            calendar.set(year, month, dayOfMonth);
            String listDate = sdf.format(calendar.getTime());
            try {
                timeStamp = Objects.requireNonNull(sdf.parse(listDate)).getTime() / 1000;
            } catch (ParseException e) {
                e.printStackTrace();
            }
            dateDisplay.setText(listDate);
            Log.d("DateStamp", String.valueOf(timeStamp));
        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show();
    }


    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.quit:
                finish();
                break;
        }
    }
}